package com.neusoft.thread8lock;

import java.util.Random;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class RWLockTest 
{

	public static void main(String[] args) 
	{
		final Data data = new Data();
		for (int i = 0; i < 3; i++) 
		{
			new Thread(new Runnable() {
				public void run() {
					for (int j = 0; j < 5; j++) 
					{
						int value=new Random().nextInt(30);
//						data.syncWrite(value);
						data.rwlWrite(value);
					}
				}
			}).start();
		}		
		for (int i = 0; i < 3; i++) 
		{
			new Thread(new Runnable() {
				public void run() {
					for (int j = 0; j < 5; j++) 
					{
//						data.syncRead();
						data.rwlRead();
					}
				}
			}).start();
		}

	}

}


class Data 
{	
	private int data;// 共享数据	
	
	private ReadWriteLock lock=new ReentrantReadWriteLock();
	
	public synchronized void syncWrite(int data) 
	{
		System.out.println(Thread.currentThread().getName() + "准备写入数据");
		try 
		{
			Thread.sleep((int)Math.random()*10);
		} 
		catch (InterruptedException e) 
		{
			e.printStackTrace();
		}
		this.data = data;
		System.out.println(Thread.currentThread().getName() + "写入" + this.data);
	}	
	public synchronized void syncRead() 
	{
		System.out.println(Thread.currentThread().getName() + "准备读取数据");
		try 
		{
			Thread.sleep(20);
		} 
		catch (InterruptedException e) 
		{
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().getName() + "读取" + this.data);
	}
	
	
	public void rwlWrite(int data)
	{
		try
		{
			lock.writeLock().lock();
			System.out.println(Thread.currentThread().getName() + ",准备写入数据");
			try 
			{
				Thread.sleep((int)Math.random()*10);
			} 
			catch (InterruptedException e) 
			{
				e.printStackTrace();
			}
			this.data = data;
			System.out.println(Thread.currentThread().getName() + ",写入" + this.data);
		}
		finally
		{
			lock.writeLock().unlock();
		}
	}
	
	
	public  void rwlRead() 
	{
		try
		{
			lock.readLock().lock();
			System.out.println(Thread.currentThread().getName() + ",准备读取数据");
			try 
			{
				Thread.sleep(20);
			} 
			catch (InterruptedException e) 
			{
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName() + ",读取" + this.data);
		}
		finally
		{
			lock.readLock().unlock();
		}
	}
}
